package top.codedance.iotp.server.net.handle.otherHandle;

import cd.io.netty.channel.ChannelHandlerContext;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.constent.Command;
import top.codedance.iotp.common.entity.CommonEntity;
import top.codedance.iotp.server.ServerApplication;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.Logger;

import javax.xml.bind.DatatypeConverter;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Formatter;

public class DownloadHandle implements Runnable {
    private static Logger logger = ServerApplication.getLogger(DownloadHandle.class);
    private static String clientFileUrl = "/iotp/client/client-%s.jar";
    private ChannelHandlerContext channelHandlerContext;
    private CommonEntity commonEntity;
    public DownloadHandle(ChannelHandlerContext channelHandlerContext, CommonEntity commonEntity){
        this.channelHandlerContext = channelHandlerContext;
        this.commonEntity = commonEntity;
    }

    @Override
    public void run() {
        byte[] body = commonEntity.getBody();
        String jsonStr = new String(body, StandardCharsets.UTF_8);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Formatter fmt = new Formatter();
        String clientJarUrl = ServerApplication.clientUpgradeReposity + fmt.format(clientFileUrl, jsonObject.getString("version"), jsonObject.getString("version"));
        downloadAndSend(clientJarUrl, jsonObject.getString("taskId"), jsonObject.getString("version"));
    }

    /**
     * 读取下载文件并发送到客户端
     * @param url
     */
    public void downloadAndSend(String url, String taskId, String version) {
        try{
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpGet httpget =new HttpGet(url);
            HttpResponse response = httpclient.execute(httpget);
            if(response.getStatusLine().getStatusCode() != 200){
                throw new Exception("Request fail.");
            }
            HttpEntity entity = response.getEntity();
            long contentLength = entity.getContentLength();
            InputStream in = entity.getContent();
            int dataIndex = 0;
            int readLength = -1;
            byte[] tmp =new byte[1024 * 1024]; //每次读1M
            long completeContentLength = 0;
            while((readLength = in.read(tmp)) != -1 && channelHandlerContext.channel().isActive()) {
                CommonEntity commonEntity2 = new CommonEntity();
                commonEntity2.setCommand(Command.DOWNLOAD_RECEIVE);
                byte[] filebody = Arrays.copyOf(tmp, readLength);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("taskId", taskId);
                jsonObject.put("version", version);
                jsonObject.put("dataIndex", dataIndex);
                jsonObject.put("contentLength", contentLength);
                jsonObject.put("bodyLength", readLength);
                jsonObject.put("body", DatatypeConverter.printHexBinary(filebody));
                commonEntity2.setBody(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
                channelHandlerContext.writeAndFlush(commonEntity2.build());
                dataIndex++;
                completeContentLength += readLength;
                logger.debug("Download complete :" + Math.floor(completeContentLength * 1.0 / contentLength * 100) + "%");
            }
            in.close();
            httpclient.close();
        } catch (Exception e){
            logger.debug(e.getMessage());
        }
    }
}
